<?php
if (!defined('IN_CONTEXT')) die('access violation error!');

class lib_xml
{
	public static $xml_file;
	public static $config = array();
	public static $_xml_obj;
	
	public static function init()
	{
		$current_class = __CLASS__;
		if(self::$_xml_obj instanceof $current_class)
		{
			return self::$_xml_obj;
		}
		else
		{
			self::$_xml_obj = new $current_class('./web.xml');
			return self::$_xml_obj;
		}
	}
	
	private function __construct($xml_file)
	{
		self::$xml_file = $xml_file;
		$this->setConfig();
	}
	
	/**
	 * 
	 * @param $xpath e.x. path1/path2. do not include root item
	 */
	public function readXml($xpath)//从xml寻找
	{
		if(extension_loaded("SimpleXML"))
		{
			//parse xpath
			$arr = array();
			$arr = explode('/', $xpath);
			if(empty($xpath) || empty($arr)) die("Can not parse this xml,please input the correct xpath to find.");
			
			//get xml object
			$xmlstr = file_get_contents(self::$xml_file);
			$xml = new SimpleXMLElement($xmlstr);
			
			//Find this value through searching this xpath.
			$i = 1;
			$count = count($arr);
			$tmp = '';
			foreach($arr as $v)
			{
				if(1 == $count)
				{
					return $xml->$v;
				}
				elseif($i < $count)
				{
					$tmp = $xml->{$v}[0];
					$i++;
				}
				elseif($i == $count)
				{
					$tmp  = $tmp->$v;
					if(!empty($tmp)) self::$config[$xpath] = $tmp;
					return $tmp;
				}
				else
				{
					die("Can not parse this xml,please input the correct xpath to find.");
				}
			}
		}
		else //another xml plugin
		{
			
		}
	}
	
	public function getConfig($xpath = false)
	{
		if(!$xpath)
		{
			return self::$config;
		}
		else
		{
			return self::$config[$xpath];
		}
	}
	
	public function setConfig() //把xml数据导入
	{
		//应该把xml数据自动导入，而不是以下手动写入,待修改
		self::$config['data/database'] = $this->readXml('data/database');
		self::$config['data/host'] = $this->readXml('data/host');
		self::$config['data/user'] = $this->readXml('data/user');
		self::$config['data/password'] = $this->readXml('data/password');
		self::$config['data/debug'] = $this->readXml('data/debug');
		self::$config['data/prefix'] = $this->readXml('data/prefix');
		self::$config['data/type'] = $this->readXml('data/type');
		
		self::$config['info/company'] = $this->readXml('info/company');
		self::$config['info/cndns'] = $this->readXml('info/cndns');
		self::$config['info/author'] = $this->readXml('info/author');
		self::$config['info/description'] = $this->readXml('info/description');
		self::$config['info/description'] = $this->readXml('info/contact');
	}
}
?>